import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button,message, Tabs, Card, Row, Col, Input, Icon, Radio, Select, Upload, Modal } from 'antd';
import React, { useState, useEffect } from 'react';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { queryRule, updateRule } from './service';
import { TwitterPicker } from 'react-color';
import reactCSS from 'reactcss';
import { Dispatch } from 'redux';
import { bdExec } from '@/helpers/RequestHelper';
import styles from './styles.less';
import { getBdToken } from '@/utils/BdHelper';
const { TabPane } = Tabs;

interface ListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  submitting: boolean;
}

/**
 * 更新节点
 */
const handleUpdate = async (fields: any) => {
  return bdExec({fn: updateRule, args: fields, successMsg: '更新成功',failMsg: '更新失败请重试！'});
};

const CrmConfigList: React.FC<ListProps> = (props) => {

  const [displayColorPicker, setDisplayColorPicker] = useState<boolean>(false);
  const [picturePreviewUrl, setPicturePreviewUrl] = useState<string>('');
  const [pictureModalVisible, setPictureModalVisible] = useState<boolean>(false);
  const [color, setColor] = useState<string>('#1890ff');
  const [picture, setPicture] = useState<any>([]);
  const [stateData, setStateData] = useState<any>({content: {}});
  const { form, form:{getFieldDecorator},submitting } = props;
  const token = getBdToken();

  const colorStyles = reactCSS({
    'default': {
      color: {
        width: '36px',
        height: '14px',
        borderRadius: '2px',
        background: `${color}`,
      },
      swatch: {
        marginTop: '8px',
        padding: '5px',
        background: '#fff',
        borderRadius: '1px',
        boxShadow: '0 0 0 1px rgba(0,0,0,.1)',
        display: 'inline-block',
        cursor: 'pointer',
      },
      popover: {
        position: 'absolute',
        zIndex: '2',
      },
      cover: {
        position: 'fixed',
        top: '0px',
        right: '0px',
        bottom: '0px',
        left: '0px',
      },
    },
  });

  useEffect(() => {
    let hide = message.loading('加载中...')
    queryRule({}).then((res:any) => {
      if(res.code === 0){
        const con = JSON.parse(res.data.listData.data[0].content || {})
        setStateData({content: con});
        buildPicture(con.logo || '');
        setColor(con.color || '');
      }else{
        message.error(res.msg);
      }
      hide()
    })
  }, [])

  const handleChangeTab = (key:any) => {
    console.log(key)
  }

  const validate = async () => {
    const { form: { validateFieldsAndScroll } } = props;
    validateFieldsAndScroll((error, values) => {
      values.color = color;
      values.fixedHeader = values.fixedHeader === 1 ? true : false;
      if(picture[0].response && picture[0].response.code === 0){
        values.logo = picture[0].response.data.file_url;
      }else{
        values.logo = picture[0].url;
      }
      if (!error) {
        handleUpdate({content: JSON.stringify(values)})
      }
    });
  }


  const handleSetPicture = (value:any) => {
    setPicture(value)
  }
  
  const previewPicture = (file:any) =>{
    setPicturePreviewUrl(file.thumbUrl);
    setPictureModalVisible(true);
  }

  const handleSetColor = (value:any) => {
    setColor(value);
  }

  const buildPicture = (url:any) => {
    if(url){
      setPicture([{
        uid: '-1',
        name: url.split('/').pop(),
        status: 'done',
        url: url,
        thumbUrl: url,
      }]);
    }
  }

  const handleChangeColor =(colorObj:any)=>{
    form.setFieldsValue({'content': colorObj.hex});
    handleSetColor(colorObj.hex);
  }

//   logo, title, desc, footer { copyright: '', links: [key, title, href, blankTarget] }
// navTheme: 'light' | 'dark'
// primaryColor: '#2F54EB'
// layout: 'sidemenu' | 'topmenu'

  return (
    <>
    <PageHeaderWrapper>

      <Card className={styles.card}>
        <Tabs defaultActiveKey="1" onChange={handleChangeTab}>
          <TabPane tab="系统配置" key="1">
            
            <Form hideRequiredMark>
              <div className={styles.title}>
                <Icon type='setting' className={styles.icon} />{'基础配置'}
              </div>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item labelCol={{span: 6}} wrapperCol={{span: 18}} label={'Logo'}>
                    {getFieldDecorator(`logo`, {
                      initialValue: picture || '',
                      rules: [{ required: false, message: '' }],
                    })(
                      <Upload
                        {...{listType: 'picture',className: 'upload-list-inline',}}
                        action="/api/admin/file/upload"
                        defaultFileList={picture}
                        fileList={picture}
                        beforeUpload={(file) => {
                          console.log('before upload file type:', file.type)
                          // todo: 这里可以对上传文件类型做限制
                          return true;
                        }}
                        data={{type: 'image'}}
                        onRemove={() => handleSetPicture([])}
                        onChange={(changeObj) => handleSetPicture(changeObj.fileList)}
                        onPreview={previewPicture}
                        headers={{
                          Authorization: `Bearer ${token}`,
                        }}
                      >
                        {
                          picture.length === 0 ? (
                            <Button>
                              <Icon type="upload" /> {'上传Logo'}
                            </Button>
                          ) : null
                        }
                      </Upload>
                    )}
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}></Col>
                <Col lg={8} md={12} sm={24}></Col>
              </Row>

              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item labelCol={{span: 6}} wrapperCol={{span: 18}} label={'系统名称'}>
                    {getFieldDecorator(`title`, {
                      initialValue: stateData.content?.title ||'',
                      rules: [{ required: false, message: '' }],
                    })(<Input/>)}
                  </Form.Item>
                  </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item labelCol={{span: 6}} wrapperCol={{span: 18}} label={'系统描述'}>
                    {getFieldDecorator(`desc`, {
                      initialValue: stateData.content?.desc || '',
                      rules: [{ required: false, message: '' }],
                    })(<Input/>)}
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24} >
                  
                </Col>
              </Row>
              
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item labelCol={{span: 6}} wrapperCol={{span: 18}} label={'著作权'}>
                    {getFieldDecorator(`copyright`, {
                      initialValue: stateData.content?.copyright || '',
                      rules: [{ required: false, message: '' }],
                    })(<Input/>)}
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>

                </Col>
                <Col lg={8} md={12} sm={24}>

                </Col>
              </Row>

              <div className={styles.title}>
                <Icon type='setting' className={styles.icon} />{'样式配置'}
              </div>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24} >
                  <Form.Item labelCol={{span: 6}} wrapperCol={{span: 18}} label={'导航主题'}>
                    {getFieldDecorator(`navTheme`, {
                      initialValue: stateData.content?.navTheme || '',
                      rules: [{ required: false, message: '' }],
                    })(
                      <Select>
                        <Select.Option key={'dark'} value={'dark'}>暗黑</Select.Option>
                        <Select.Option key={'light'} value={'light'}>光亮</Select.Option>
                      </Select>
                    )}
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item labelCol={{span: 6}} wrapperCol={{span: 18}} label={'主题颜色'}>
                    <div style={colorStyles.swatch} onClick={ () => setDisplayColorPicker(!displayColorPicker) }>
                      <div style={colorStyles.color} ></div>
                    </div>
                    {displayColorPicker ?
                      <div style={{ position:'absolute', zIndex: 2}}>
                        <div style={{position: 'fixed', top: '0px', right: '0px',bottom: '0px',left: '0px'}} onClick={ () => setDisplayColorPicker(false) }></div>
                        <TwitterPicker color={ color } onChange={ (val) => handleChangeColor(val) } />
                      </div>
                      : null
                    }
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>

                </Col>
              </Row>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24} >
                  <Form.Item labelCol={{span: 6}} wrapperCol={{span: 18}} label={'固定头部'}>
                    {getFieldDecorator(`fixedHeader`, {
                      initialValue: stateData.content?.fixedHeader == true ? 1 : 0,
                      rules: [{ required: false, message: '' }],
                    })(
                      <Select>
                        <Select.Option key={'header1'} value={1}>是</Select.Option>
                        <Select.Option key={'header0'} value={0}>否</Select.Option>
                      </Select>
                    )}
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item labelCol={{span: 6}} wrapperCol={{span: 18}} label={'菜单布局'}>
                    {getFieldDecorator(`layout`, {
                      initialValue: stateData.content?.layout || '',
                      rules: [{ required: false, message: '' }],
                    })(
                      <Select>
                        <Select.Option key={'sidemenu'} value={'sidemenu'}>左边</Select.Option>
                        <Select.Option key={'topmenu'} value={'topmenu'}>顶部</Select.Option>
                      </Select>
                    )}
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  
                </Col>
              </Row>
              {/* fixedHeader */}
            </Form>
          </TabPane>
          <TabPane tab="系统运行信息" key="2">
            <Form hideRequiredMark>
              <div className={styles.title}>
                <Icon type='setting' className={styles.icon} />{'基本信息'}
              </div>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item labelCol={{span: 6}} wrapperCol={{span: 18}} label={'BD版本'}>
                    {getFieldDecorator(`system`, {
                      initialValue: stateData.content?.system || '',
                      rules: [{ required: false, message: '' }],
                    })(<Input/>)}
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24} >
                </Col>
                <Col lg={8} md={12} sm={24}>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24} >
                  <Form.Item labelCol={{span: 6}} wrapperCol={{span: 18}} label={'php版本'}>
                    {getFieldDecorator(`php`, {
                      initialValue: stateData.content?.php || '',
                      rules: [{ required: false, message: '' }],
                    })(<Input/>)}
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item labelCol={{span: 6}} wrapperCol={{span: 18}} label={'mysql版本'}>
                    {getFieldDecorator(`mysql`, {
                      initialValue: stateData.content?.mysql || '',
                      rules: [{ required: false, message: '' }],
                    })(<Input/>)}
                  </Form.Item>
                </Col>
                <Col lg={7} md={12} sm={24}>

                </Col>
              </Row>
            </Form>
          </TabPane>
        </Tabs>
      </Card>
    </PageHeaderWrapper>
    <Modal
      title={'图片预览'}
      visible={pictureModalVisible}
      onOk={() => setPictureModalVisible(false)}
      onCancel={() => setPictureModalVisible(false)}
      afterClose={() => setPictureModalVisible(false)}
      footer={null}
    >
      <img src={picturePreviewUrl} width={'100%'}/>
    </Modal>
    <FooterToolbar>
      <Button type="primary" onClick={validate} loading={submitting}>
        提交
      </Button>
    </FooterToolbar>
    </>
  );
};

export default Form.create<ListProps>()(CrmConfigList);
